﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace System
{
    /// <summary>
    /// 提供与文件日志的交互。
    /// </summary>
    public class FileLog:IDisposable
    {
        private string _Source;
        /// <summary>
        /// 获取应用程序在本地计算机上注册时所采用的源名称。
        /// </summary>
        public string Source
        {
            get
            {
                return this._Source;
            }
        }

        private DateTime LastLogTime;
        private readonly DirectoryInfo LogDirectory;
        private StreamWriter LogWriter;

        /// <summary>
        /// 初始化 <see cref="System.FileLog"/> 的新实例。
        /// </summary>
        /// <param name="source">日志文件前缀。</param>
        public FileLog(string source) : this("LOG", source) { }

        /// <summary>
        /// 初始化 <see cref="System.FileLog"/> 的新实例。
        /// </summary>
        /// <param name="direPath">日志目录。</param>
        /// <param name="source">日志文件前缀。</param>
        public FileLog(string direPath, string source)
        {
            this._Source = source;
            this.LogDirectory = IOExts.CreateDirectory(GA.FullPath(direPath));
            this.CreateWriter();
        }

        private void CreateWriter()
        {
            try
            {

                this.Close();
                this.LastLogTime = DateTime.Now.Date;
                this.LogWriter = new StreamWriter(Path.Combine(this.LogDirectory.FullName, this._Source + this.LastLogTime.ToString("yyyy-MM-dd") + ".log"), true, Encoding.UTF8);

            }
            catch(Exception)
            {

            }
        }

        private void ClearOldLogs()
        {
            try
            {
                foreach(var file in this.LogDirectory.GetFiles())
                {
                    if((LastLogTime - file.CreationTime).Days > 10)
                    {
                        try
                        {
                            file.Delete();
                        }
                        catch(Exception)
                        {
                        }
                    }
                }
            }
            catch(Exception)
            {
            }
        }

        /// <summary>
        /// 写入一个错误日志。
        /// </summary>
        /// <param name="message">日志内容</param>
        public void WriteError(string message)
        {
            WriteLog(EventLogEntryType.Error, message);
        }

        /// <summary>
        /// 写入一个提醒日志。
        /// </summary>
        /// <param name="message">日志内容</param>
        public void WriteInfo(string message)
        {
            WriteLog(EventLogEntryType.Information, message);
        }

        /// <summary>
        /// 写入一个成功日志。
        /// </summary>
        /// <param name="message">日志内容</param>
        public void WriteSuccess(string message)
        {
            WriteLog(EventLogEntryType.SuccessAudit, message);
        }

        /// <summary>
        /// 写入一个失败日志。
        /// </summary>
        /// <param name="message">日志内容</param>
        public void WriteFailure(string message)
        {
            WriteLog(EventLogEntryType.FailureAudit, message);
        }

        /// <summary>
        /// 写入一个警告日志。
        /// </summary>
        /// <param name="message">日志内容</param>
        public void WriteWarning(string message)
        {
            WriteLog(EventLogEntryType.Warning, message);
        }

        private void WriteLog(EventLogEntryType type, string message)
        {
            if(this.LogWriter == null || DateTime.Now.Date != this.LastLogTime)
            {
                this.CreateWriter();
                this.ClearOldLogs();
            }
            try
            {
                this.LogWriter.WriteLine(type.ToString() + "  " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n" + message + "\r\n");
                this.LogWriter.Flush();
            }
            catch(Exception)
            {
                this.Close();
            }
        }


        #region IDisposable 成员

        /// <summary>
        /// 关闭日志。
        /// </summary>
        public void Close()
        {
            if(this.LogWriter != null)
            {
                try
                {
                    this.LogWriter.Close();
                }
                catch(Exception) { }
                this.LogWriter = null;
            }
        }
        void IDisposable.Dispose()
        {
            this.Close();
        }

        /// <summary>
        /// 析构函数。
        /// </summary>
        ~FileLog()
        {
            this.Close();
        }

        #endregion
    }
}
